package cn.bookCity.servlet;

import static org.hamcrest.CoreMatchers.nullValue;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.ConvertUtils;

import cn.bookCity.Exception.MyException;
import cn.bookCity.convert.MyConvert;
import cn.bookCity.domain.OrderPage;
import cn.bookCity.domain.Orderitem;
import cn.bookCity.domain.Orders;
import cn.bookCity.domain.Products;
import cn.bookCity.domain.Show;
import cn.bookCity.domain.User;
import cn.bookCity.service.OrderService;
import cn.bookCity.service.ProductService;
import cn.bookCity.util.BeanFactory;
import cn.bookCity.util.UUIDUtils;

@WebServlet("/book/order")
public class OrderServlet  extends BaseServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public String creatOd(HttpServletRequest request,HttpServletResponse response)throws Exception {
		
		Orders order=new Orders();
		HttpSession session=request.getSession();
		System.out.println("添加订单！");
		@SuppressWarnings("unchecked")
		HashMap<Products, Integer> cart=(HashMap<Products, Integer>) session.getAttribute("cart");
		User user=(User) session.getAttribute("user");
		if(user!=null) {
			order.setUser(user);
			order.setId(UUIDUtils.getCode());
			String receiverAddress=request.getParameter("receiverAddress");
			order.setReceiverAddress(receiverAddress);
			String receiverName=request.getParameter("receiverName");
			order.setReceiverName(receiverName);
			String receiverPhone=request.getParameter("receiverPhone");
			order.setReceiverPhone(receiverPhone);
	        String money=request.getParameter("money");
	        order.setMoney(Double.parseDouble(money));
	        ConvertUtils.register(new MyConvert(), Date.class);
	        List<Orderitem> list=new ArrayList<>();
	        for(Products p:cart.keySet()) {
	        	Orderitem orderitem=new Orderitem();
	        	orderitem.setOrder_id(order.getId());
	        	orderitem.setProduct_id(p.getId());
	        	int buynum = cart.get(p);
				orderitem.setBuynum(buynum);
				list.add(orderitem);
	        }
			order.setOrderitems(list);
			OrderService os=(OrderService)BeanFactory.getBean("OrderService");
			try {
				os.addOrder(order);
			}catch (Exception e) {
				request.setAttribute("msg", "订单创建失败");
			    return "/errorMessage.jsp";
			}
			return "/createOrder-success.jsp";
		}
	   return "/login.jsp";
	}
	public String show(HttpServletRequest request,HttpServletResponse response)throws Exception {
		System.out.println("查询订单");
		int pageSize=4;
		HttpSession session=request.getSession();
		User user=(User) session.getAttribute("user");
		if(user!=null) {
			OrderPage page=new OrderPage();
			String pageIndex=request.getParameter("pageIndex");
			int currentIndex=1;
			if(pageIndex==null) {
				currentIndex=1;
			}else {
				currentIndex=Integer.parseInt(pageIndex);
			}
			OrderService os=(OrderService)BeanFactory.getBean("OrderService");
			int count=os.getCount(user.getId());
			int totalPages=(count%pageSize)==0?(count/pageSize):((count/pageSize)+1);
			if(currentIndex<=1) {
				currentIndex=1;
			}else if(currentIndex>=totalPages) {
				currentIndex=totalPages;
			}
			page.setCurrentIndex(currentIndex);
			page.setTotalpages(totalPages);
		    List<Show> list=new ArrayList<>();
		    int startNo=(currentIndex-1)*pageSize;
			List<Orders> orders=os.getPageOrders(startNo, pageSize,user.getId());
			ProductService p=(ProductService)BeanFactory.getBean("ProductService");
			if(orders!=null) {
				for(Orders order:orders) {
					System.out.println(order.getMoney());
					Show show=new Show();
					show.setOrder(order);
					List<Products> list2=new ArrayList<>();
					for(Orderitem item:os.getOrderItem(order.getId())) {
						String id=item.getProduct_id();
						Products products=p.getProduct(id);
		                list2.add(products);
					}
					show.setProducts(list2);
					list.add(show);
				}
			}
			page.setShows(list);
			request.setAttribute("orderList", page);
	        return "/orderlist.jsp";		
		}
      		
		return "/login.jsp";
	}
	
	public String showAllOrders(HttpServletRequest request,HttpServletResponse response) {
		OrderService os = (OrderService)BeanFactory.getBean("OrderService");
		List<Orders> orders = os.getOrders();
		
		request.setAttribute("orderList", orders);
		
		return "/manager/order/orderList.jsp";
	}
	
	public String findOrderById(HttpServletRequest request,HttpServletResponse response) {
		OrderService os = (OrderService)BeanFactory.getBean("OrderService");
		ProductService p = (ProductService)BeanFactory.getBean("ProductService");
		String id = request.getParameter("id");
		
		Orders order = os.getOrdersById(id);
		
		List<Orderitem> orderitems = os.getOrderItem(id);
		List<Products> products = new ArrayList<>();
		
		if(orderitems!=null){
			for (Orderitem orderitem : orderitems) {
				String product_id = orderitem.getProduct_id();
				Products product = p.getProduct(product_id);
				product.setPnum(orderitem.getBuynum());
				products.add(product);
			}
		}
		
		request.setAttribute("productList", products);
		request.setAttribute("order", order);
		return "/manager/order/order.jsp";
		
	}
	
}
